package cn.flexui.flexuiserver.ai.memory;

import cn.flexui.flexuiserver.domain.constant.enums.RedisKeyEnum;
import org.springframework.ai.chat.memory.ChatMemory;
import org.springframework.ai.chat.messages.Message;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
public class RedisChatMemory implements ChatMemory {

    private final RedisTemplate<String, Message> redisTemplate;

    public RedisChatMemory(RedisTemplate<String, Message> redisTemplate) {
        this.redisTemplate = redisTemplate;
    }

    @Override
    public void add(String conversationId, List<Message> messages) {
        String key = RedisKeyEnum.CHAT_MEMORY.getKey(conversationId);
        redisTemplate.opsForList().rightPushAll(key, messages);
    }

    @Override
    public List<Message> get(String conversationId, int lastN) {
        String key = RedisKeyEnum.CHAT_MEMORY.getKey(conversationId);
        return redisTemplate.opsForList().range(key, 0, -lastN);

    }

    @Override
    public void clear(String conversationId) {
        String key = RedisKeyEnum.CHAT_MEMORY.getKey(conversationId);
        redisTemplate.delete(key);
    }

}
